<?php

if (!defined('DIR_SEP')) {
    define('DIR_SEP', DIRECTORY_SEPARATOR);
}

if (!defined('MODULES_DIR')) {
    define('MODULES_DIR', dirname(__FILE__).DIR_SEP."..".DIR_SEP);
}

require_once(MODULES_DIR.'db.inc');
require_once(MODULES_DIR.'config.inc');

class FeedItem
{
	protected $db;
	public $id;
	public $feedId;
	public $entryDate;
	public $title;
	public $content;
	public $link;
	public $feedName;
	public $viewCount;
	public $permalink;
	
	function __construct()
	{
		$this->db = DB::getInstance()->getDB();
	}
	
	function addItem($feedId,$title,$link,$content,$feedTime)
	{
		try
		{
			$content = str_replace("'","\'",$content);

			$permalink = Util::cutStringFullWords($title,100);
			$permalink = preg_replace("[\W]","_",$permalink);
			$permalink .= "_";
			
			while(strpos($permalink,"__",0)!= false) 
				$permalink = str_replace("__","_",$permalink);
				
			$sql ="insert into t_feed_item (feed_id,entry_date,title,content,link,view_count,permalink)
					values (".$feedId.",'".date('YmdHis',$feedTime)."','".$title."','".$content."','".$link."',0,'".$permalink."')";

			$query = mysql_query($sql,$this->db);

			if (!$query)
				throw new Exception(mysql_error());
			
			return true;
		}
		catch(Exception $ex)
		{
			return false;
		}		
	}

	/*
	 * Promotes the view count of the feed item for statistics.
	 */
	function promoteViewCount()
	{
		try
		{
			$sql = "update t_feed_item set view_count = view_count + 1 where id = ".$this->id;
	
			//As the object is being cached, it loses it's connectivity to the DB, so don't use the member _db object.
			$query = mysql_query($sql,DB::getInstance()->getDB());
	
			if (!$query)
				throw new Exception(mysql_error());
		
			return true;
		}
		catch(Exception $ex)
		{
			return false;
		}		
	}
	
	function load($itemId)
	{
		try
		{
			$sql ="select tfi.id,tfi.feed_id,tfi.entry_date,tfi.title,tfi.content,tfi.link,
					tf.feed_name as feed_name,tfi.view_count,tfi.permalink
					FROM t_feed_item tfi inner join t_feed tf on tf.id = tfi.feed_id 
					WHERE tfi.id = ".$itemId;

			$query = mysql_query($sql,$this->db);

			if (!$query)
				throw new Exception(mysql_error());
						
			$row = mysql_fetch_row($query);
							
			$this->id = $itemId;
			$this->feedId = $row[1];
			$this->entryDate = strtotime($row[2]);
			$this->title = $row[3];
			$this->content = $row[4];
			$this->link = $row[5];
			$this->feedName = $row[6];
			$this->viewCount = $row[7];
			$this->permalink = $row[8];
			
			return true;
		}
		catch(Exception $ex)
		{
			return false;
		}	
	}

	public function getUrl()
	{
		global $G_HOME;
		
		$config = Config::getInstance();
		$usePermalinks = $config->get('/site/features/permalinks/@enabled');
		
		$link = '';
		
		if($usePermalinks == '1' && strlen($this->permalink) > 0)
			$link = strtolower(Util::combinePath($G_HOME,"feed/".$this->permalink.$this->id));
		else
			$link = Util::combinePath($G_HOME,"index.php?pg=feed&amp;feedId=".$this->id);
			
		return $link;
	}
	
	static function getCount()
	{
		$sql = "select count(1) as counter from t_feed_item";
		$query = mysql_query($sql,DB::getInstance()->getDB());
		if (!$query)
			throw new Exception(mysql_error());
		$row = mysql_fetch_assoc($query);
		return $row["counter"];
	}
	
	static function getSourceCount($sourceId)
	{
		$sql = "select count(1) as counter from t_feed_item where feed_id =  ".$sourceId;
		$query = mysql_query($sql,DB::getInstance()->getDB());
		if (!$query)
			throw new Exception(mysql_error());
		$row = mysql_fetch_assoc($query);
		return $row["counter"];
	}

	static function getCategoryCount($categoryId)
	{
		$sql = "select count(1) as counter 
				from t_feed_item tfi
				inner join t_feed_tag_item tfti on tfti.feed_id = tfi.feed_id 
				where tfti.tag_id = $categoryId";
		$query = mysql_query($sql,DB::getInstance()->getDB());
		if (!$query)
			throw new Exception(mysql_error());
		$row = mysql_fetch_assoc($query);
		return $row["counter"];
	}
	
	static function getCategoryItems($categoryId,$orderBy,$startRow,$count)
	{
		try
		{
			$orderBy = trim($orderBy);
			
			if( strlen($orderBy) > 0 )
				$orderBy = ' order by '.$orderBy.' ';
				
			$count = ( $count <= 0) ? DB::$ALL_ROWS : $count;

			$sql ="select tfi.id,tfi.feed_id,tfi.entry_date,tfi.title,tfi.content,tfi.link,
					tf.feed_name as feed_name,tfi.view_count,tfi.permalink
					FROM t_feed_item tfi 
					inner join t_feed tf on tf.id = tfi.feed_id 
					inner join t_feed_tag_item tfti on tfti.feed_id = tf.id
					where tfti.tag_id = ".$categoryId.
					" ".$orderBy." limit ".$startRow.",".$count;

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$result = array();
			
			while( list($id,$feed_id,$entry_date,$title,$content,$link,$feedName,$viewCount,$permalink) = mysql_fetch_row($query))
			{
				$feedItem = new FeedItem(DB::getInstance()->getDB());
				
				$feedItem->id = $id;
				$feedItem->feedId = $feed_id;
				$feedItem->entryDate = strtotime($entry_date);
				$feedItem->title = $title;
				$feedItem->content = $content;
				$feedItem->link = $link;
				$feedItem->feedName = $feedName;
				$feedItem->viewCount = $viewCount;
				$feedItem->permalink = $permalink;
				
				$result[] = $feedItem;
			}

			return $result;
		}
		catch(Exception $ex)
		{
			die("feedItem->getCategoryItems:".$ex->getMessage());
			return null;
		}
	}
	
	static function getSourceItems($sourceId,$orderBy,$startRow,$count)
	{
		try
		{
			$orderBy = trim($orderBy);
			
			if( strlen($orderBy) > 0 )
				$orderBy = ' order by '.$orderBy.' ';
				
			$count = ( $count <= 0) ? DB::$ALL_ROWS : $count;

			$sql ="select tfi.id,tfi.feed_id,tfi.entry_date,tfi.title,tfi.content,tfi.link,
					tf.feed_name as feed_name,tfi.view_count,tfi.permalink
					FROM t_feed_item tfi 
					inner join t_feed tf on tf.id = tfi.feed_id 
					where tf.id = ".$sourceId.
					" ".$orderBy." limit ".$startRow.",".$count;

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$result = array();
			
			while( list($id,$feed_id,$entry_date,$title,$content,$link,$feedName,$viewCount,$permalink) = mysql_fetch_row($query))
			{
				$feedItem = new FeedItem(DB::getInstance()->getDB());
				
				$feedItem->id = $id;
				$feedItem->feedId = $feed_id;
				$feedItem->entryDate = strtotime($entry_date);
				$feedItem->title = $title;
				$feedItem->content = $content;
				$feedItem->link = $link;
				$feedItem->feedName = $feedName;
				$feedItem->viewCount = $viewCount;
				$feedItem->permalink = $permalink;
				
				$result[] = $feedItem;
			}

			return $result;
		}
		catch(Exception $ex)
		{
			die("feedItem->getSourceItems:".$ex->getMessage());
			return null;
		}
	}
	
	static function getItems($orderBy,$startRow,$count)
	{
		try
		{			
			$orderBy = trim($orderBy);
			
			if( strlen($orderBy) > 0 )
				$orderBy = ' order by '.$orderBy.' ';
			
			$count = ( $count <= 0) ? DB::$ALL_ROWS : $count;
			
			$sql ="select tfi.id,tfi.feed_id,tfi.entry_date,tfi.title,tfi.content,tfi.link,
					tf.feed_name as feed_name,tfi.view_count,tfi.permalink
					FROM t_feed_item tfi 
					inner join t_feed tf on tf.id = tfi.feed_id".$orderBy." limit ".$startRow.",".$count;

			$query = mysql_query($sql,DB::getInstance()->getDB());

			if (!$query)
				throw new Exception(mysql_error());
			
			$result = array();
			
			while( list($id,$feed_id,$entry_date,$title,$content,$link,$feedName,$viewCount,$permalink) = mysql_fetch_row($query))
			{
				$feedItem = new FeedItem(DB::getInstance()->getDB());
				
				$feedItem->id = $id;
				$feedItem->feedId = $feed_id;
				$feedItem->entryDate = strtotime($entry_date);
				$feedItem->title = $title;
				$feedItem->content = $content;
				$feedItem->link = $link;
				$feedItem->feedName = $feedName;
				$feedItem->viewCount = $viewCount;
				$feedItem->permalink = $permalink;
				
				$result[] = $feedItem;
			}

			return $result;
		}
		catch(Exception $ex)
		{
			die("feedItem->getItems:".$ex->getMessage());
			return null;
		}
	}
}

?>